<template>
  <div class="edit-invitation-container">
    <h1 class="page-title">编辑帖子</h1>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-loading :loading="loading" text="加载中..."></el-loading>
    </div>

    <!-- 编辑表单 -->
    <form v-else class="post-form" @submit.prevent="handleSubmit">
      <!-- 服务器错误提示 -->
      <div class="server-error" v-if="errors.server">
        <i class="fas fa-exclamation-circle"></i>
        <span>{{ errors.server }}</span>
      </div>

      <!-- 帖子标题 -->
      <div class="form-group">
        <label for="title">标题 <span class="required">*</span></label>
        <input
            type="text"
            id="title"
            v-model="formData.postTitle"
            :class="{ 'error': errors.postTitle }"
            placeholder="请输入帖子标题"
            maxlength="100"
        >
        <div class="input-hint">
          <span class="char-count">{{ formData.postTitle.length }}/100</span>
          <p class="error-message" v-if="errors.postTitle">{{ errors.postTitle }}</p>
        </div>
      </div>

      <!-- 帖子内容 -->
      <div class="form-group">
        <label for="content">内容 <span class="required">*</span></label>
        <textarea
            id="content"
            v-model="formData.postContent"
            :class="{ 'error': errors.postContent }"
            rows="10"
            placeholder="请输入帖子内容，详细描述可以获得更多关注..."
            maxlength="10000"
        ></textarea>
        <div class="input-hint">
          <span class="char-count">{{ formData.postContent.length }}/10000 字符</span>
          <p class="error-message" v-if="errors.postContent">{{ errors.postContent }}</p>
        </div>
      </div>

      <!-- 帖子分类 -->
      <div class="form-group">
        <label for="category">分类 <span class="required">*</span></label>
        <select
            id="category"
            v-model="formData.categoryName"
            :class="{ 'error': errors.categoryName }"
        >
          <option value="">请选择分类</option>
          <option value="技术讨论">技术讨论</option>
          <option value="经验分享">经验分享</option>
          <option value="问题求助">问题求助</option>
          <option value="其他">其他</option>
        </select>
        <p class="error-message" v-if="errors.categoryName">{{ errors.categoryName }}</p>
      </div>

      <!-- 帖子状态 -->
      <div class="form-group">
        <label for="status">状态 <span class="required">*</span></label>
        <select
            id="status"
            v-model="formData.status"
            :class="{ 'error': errors.status }"
        >
          <option :value="1">发布</option>
          <option :value="0">草稿</option>
        </select>
        <p class="error-message" v-if="errors.status">{{ errors.status }}</p>
      </div>

      <!-- 封面图片 -->
      <div class="form-group">
        <label for="cover_Image">封面图片</label>
        <input
            type="file"
            id="cover_Image"
            accept="image/*"
            @change="handleImageUpload"
        >
        <p class="error-message" v-if="errors.coverImage">{{ errors.coverImage }}</p>
        
        <!-- 当前图片预览 -->
        <div class="current-image" v-if="currentImageUrl && !imagePreviewUrl">
          <p>当前封面：</p>
          <img :src="currentImageUrl" alt="当前封面" class="current-cover">
        </div>
        
        <!-- 新图片预览 -->
        <div class="image-preview" v-if="imagePreviewUrl">
          <p>新封面预览：</p>
          <img :src="imagePreviewUrl" alt="封面预览">
          <button type="button" class="remove-image" @click="clearImage">×</button>
        </div>
        
        <div class="upload-hint" v-if="!imagePreviewUrl && !currentImageUrl">
          <small>支持jpg、png、gif格式，文件大小不超过5MB。图片将高度压缩优化，建议使用简单图像（如纯色背景、简单形状等）</small>
        </div>
      </div>

      <!-- 提交按钮 -->
      <div class="form-actions">
        <button
            type="submit"
            class="submit-btn"
            :disabled="isSubmitting"
        >
          <span v-if="!isSubmitting">
            {{ formData.status === 1 ? '更新帖子' : '保存草稿' }}
          </span>
          <span v-if="isSubmitting">
            <i class="fas fa-spinner fa-spin"></i> 处理中...
          </span>
        </button>
        <button
            type="button"
            class="cancel-btn"
            @click="handleCancel"
            :disabled="isSubmitting"
        >
          取消
        </button>
      </div>
    </form>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { invitationAPI } from '../services/api';

const route = useRoute();
const router = useRouter();

// 表单数据
const formData = ref({
  id: null,
  postTitle: '',
  postContent: '',
  categoryName: '',
  coverImage: '',
  status: 1
});

// 错误信息
const errors = reactive({
  postTitle: '',
  postContent: '',
  categoryName: '',
  status: '',
  coverImage: '',
  server: ''
});

// 状态管理
const loading = ref(false);
const isSubmitting = ref(false);
const imagePreviewUrl = ref('');
const currentImageUrl = ref('');
const isDirty = ref(false);

// 当前用户
const currentUser = computed(() => {
  const userInfo = localStorage.getItem('userInfo');
  return userInfo ? JSON.parse(userInfo) : null;
});

// 超级图片压缩
const superCompressImage = async (file) => {
  return new Promise((resolve) => {
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    const img = new Image();
    
    img.onload = () => {
      // 极小尺寸以适应数据库
      let width = 150;
      let height = 100;
      
      // 按比例计算尺寸
      const ratio = Math.min(width / img.width, height / img.height);
      width = Math.floor(img.width * ratio);
      height = Math.floor(img.height * ratio);
      
      canvas.width = width;
      canvas.height = height;
      
      // 绘制并压缩
      ctx.drawImage(img, 0, 0, width, height);
      
      // 极限压缩质量
      let compressed = canvas.toDataURL('image/jpeg', 0.1);
      
      // 如果还是过大，再次缩小
      if (compressed.length > 5000) {
        canvas.width = Math.max(width * 0.6, 80);
        canvas.height = Math.max(height * 0.6, 60);
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
        compressed = canvas.toDataURL('image/jpeg', 0.05);
      }
      
      resolve(compressed);
    };
    
    img.src = URL.createObjectURL(file);
  });
};

// 图片上传处理
const handleImageUpload = async (e) => {
  const file = e.target.files?.[0];
  if (!file) return;
  
  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    errors.coverImage = '请选择图片文件';
    return;
  }
  
  // 验证文件大小 (5MB)
  if (file.size > 5 * 1024 * 1024) {
    errors.coverImage = '图片大小不能超过5MB';
    return;
  }
  
  try {
    // 使用超级压缩
    const compressedBase64 = await superCompressImage(file);
    
    // 检查最终大小
    if (compressedBase64.length > 5000) {
      errors.coverImage = '图片太复杂，请选择更简单的图像（如纯色背景、简单形状等）';
      return;
    }
    
    // 保存Base64字符串
    formData.value.coverImage = compressedBase64;
    imagePreviewUrl.value = compressedBase64;
    
    // 清除错误信息
    errors.coverImage = '';
    isDirty.value = true;
    
    console.log('图片上传成功！最终大小:', compressedBase64.length, '字符');
    
  } catch (error) {
    console.error('图片处理失败:', error);
    errors.coverImage = '图片处理失败，请重试';
  }
};

// 移除图片
const clearImage = () => {
  formData.value.coverImage = '';
  imagePreviewUrl.value = '';
  document.getElementById('cover_Image').value = '';
  errors.coverImage = '';
  isDirty.value = true;
};

// 获取帖子详情
const fetchInvitationDetail = async () => {
  try {
    loading.value = true;
    const postid = parseInt(route.params.id);
    const response = await invitationAPI.queryInvitationDetail(postid);
    const invitation = response.data;
    
    // 检查权限
    if (!currentUser.value || currentUser.value.name !== invitation.userName) {
      ElMessage.error('您只能编辑自己的帖子');
      router.push('/invitations');
      return;
    }
    
    // 填充表单数据
    formData.value = {
      id: invitation.id,
      postTitle: invitation.postTitle || '',
      postContent: invitation.postContent || '',
      categoryName: invitation.categoryName || '',
      coverImage: invitation.coverImage || '',
      status: invitation.status !== undefined ? invitation.status : 1
    };
    
    // 设置当前图片URL
    if (invitation.coverImage) {
      currentImageUrl.value = invitation.coverImage;
    }
    
  } catch (error) {
    console.error('获取帖子详情失败:', error);
    ElMessage.error(error.message || '获取帖子详情失败');
    router.push('/invitations');
  } finally {
    loading.value = false;
  }
};

// 表单验证
const validateForm = () => {
  let isValid = true;
  // 清空所有错误
  Object.keys(errors).forEach(key => errors[key] = '');

  // 验证标题
  if (!formData.value.postTitle.trim()) {
    errors.postTitle = '帖子标题不可为空';
    isValid = false;
  } else if (formData.value.postTitle.length > 100) {
    errors.postTitle = '标题不能超过100字符';
    isValid = false;
  }

  // 验证内容
  if (!formData.value.postContent.trim()) {
    errors.postContent = '帖子内容不可为空';
    isValid = false;
  } else if (formData.value.postContent.length > 10000) {
    errors.postContent = '帖子内容不能超过10000字符';
    isValid = false;
  }

  // 验证分类
  if (!formData.value.categoryName) {
    errors.categoryName = '分类名不可空';
    isValid = false;
  }

  // 验证状态
  if (formData.value.status !== 0 && formData.value.status !== 1) {
    errors.status = '请选择正确的状态';
    isValid = false;
  }

  return isValid;
};

// 提交表单
const handleSubmit = async () => {
  if (!validateForm()) {
    return;
  }

  try {
    isSubmitting.value = true;
    
    // 构建更新数据（包含ID）
    const updateData = {
      id: formData.value.id,
      postTitle: formData.value.postTitle,
      postContent: formData.value.postContent,
      categoryName: formData.value.categoryName,
      status: formData.value.status
    };
    
    // 如果有新图片，添加到更新数据中
    if (imagePreviewUrl.value) {
      updateData.coverImage = formData.value.coverImage;
    }
    
    console.log('更新数据:', updateData);
    
    await invitationAPI.updateInvitation(updateData);
    
    ElMessage.success('帖子更新成功！');
    isDirty.value = false;
    router.push(`/invitation/${formData.value.id}`);
  } catch (error) {
    console.error('更新失败:', error);
    
    // 处理错误
    if (error.message.includes('Data too long for column')) {
      if (error.message.includes('post_content')) {
        errors.postContent = '帖子内容过长，请缩短内容后重试';
      } else if (error.message.includes('cover_image')) {
        errors.coverImage = '图片数据过大，请选择更小的图片';
      } else if (error.message.includes('post_title')) {
        errors.postTitle = '帖子标题过长，请缩短后重试';
      } else {
        errors.server = '数据过长，请检查输入内容';
      }
    } else {
      errors.server = error.message || '网络错误，请稍后重试';
    }
  } finally {
    isSubmitting.value = false;
  }
};

// 取消操作
const handleCancel = () => {
  if (!isDirty.value) {
    router.back();
    return;
  }

  if (confirm('确定要取消编辑吗？已修改的内容将会丢失。')) {
    router.back();
  }
};

// 监听页面刷新或关闭事件
window.addEventListener('beforeunload', (e) => {
  if (isDirty.value && !isSubmitting.value) {
    e.preventDefault();
    e.returnValue = '您有未保存的内容，确定要离开吗？';
    return e.returnValue;
  }
});

// 组件挂载时获取数据
onMounted(() => {
  if (!currentUser.value) {
    ElMessage.error('请先登录');
    router.push('/login');
    return;
  }
  
  fetchInvitationDetail();
});
</script>

<style scoped>
/* 复用CreateInvitation.vue的样式 */
.edit-invitation-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 0 20px;
}

.page-title {
  color: #333;
  border-bottom: 2px solid #42b983;
  padding-bottom: 10px;
  margin-bottom: 30px;
}

.loading-container {
  height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.server-error {
  background-color: #fff1f0;
  border: 1px solid #ffa39e;
  border-radius: 4px;
  padding: 12px 16px;
  margin-bottom: 20px;
  color: #f5222d;
  display: flex;
  align-items: center;
}

.server-error i {
  margin-right: 8px;
  font-size: 18px;
}

.post-form {
  background-color: #fff;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.form-group {
  margin-bottom: 25px;
}

label {
  display: block;
  margin-bottom: 8px;
  color: #555;
  font-weight: 500;
}

.required {
  color: #ff4d4f;
}

input, textarea, select {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
  transition: border-color 0.2s;
}

input:focus, textarea:focus, select:focus {
  border-color: #42b983;
  outline: none;
  box-shadow: 0 0 0 2px rgba(66, 185, 131, 0.2);
}

textarea {
  resize: vertical;
}

.error {
  border-color: #ff4d4f !important;
}

.error:focus {
  box-shadow: 0 0 0 2px rgba(255, 77, 79, 0.2);
}

.error-message {
  color: #ff4d4f;
  font-size: 14px;
  margin-top: 5px;
  min-height: 20px;
}

.input-hint {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.char-count {
  font-size: 14px;
  color: #888;
}

/* 当前图片和预览 */
.current-image, .image-preview {
  margin-top: 15px;
}

.current-image p, .image-preview p {
  margin: 0 0 10px 0;
  color: #666;
  font-size: 14px;
}

.current-cover, .image-preview img {
  max-width: 200px;
  max-height: 150px;
  border-radius: 8px;
  border: 1px solid #ddd;
}

.image-preview {
  position: relative;
  display: inline-block;
}

.remove-image {
  position: absolute;
  top: -10px;
  right: -10px;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background: #ff4d4f;
  color: white;
  border: none;
  cursor: pointer;
  font-size: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-hint {
  margin-top: 10px;
  color: #999;
  font-size: 12px;
}

.form-actions {
  display: flex;
  gap: 15px;
  justify-content: center;
  margin-top: 30px;
}

.submit-btn, .cancel-btn {
  padding: 12px 30px;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  min-width: 120px;
}

.submit-btn {
  background: #42b983;
  color: white;
}

.submit-btn:hover:not(:disabled) {
  background: #369970;
  transform: translateY(-2px);
}

.submit-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.cancel-btn {
  background: #f5f5f5;
  color: #666;
}

.cancel-btn:hover:not(:disabled) {
  background: #e9e9e9;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .edit-invitation-container {
    padding: 10px;
  }
  
  .post-form {
    padding: 20px;
  }
  
  .form-actions {
    flex-direction: column;
  }
}
</style>